package com.liu.sunnyday.controller;

/**
 * chance！Time
 *
 * @author liuqian
 * @date 2022-07-12 0:31
 * *
 */

import com.alibaba.dubbo.config.annotation.Reference;
import com.liu.sunnyday.constant.MessageConstant;
import com.liu.sunnyday.entity.Result;
import com.liu.sunnyday.pojo.Menu;
import com.liu.sunnyday.pojo.Role;
import com.liu.sunnyday.service.MemberService;
import com.liu.sunnyday.service.MenuService;
import com.liu.sunnyday.service.UserService;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.User;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Set;

/**
 * 用户名回显
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Reference
    private UserService userService;

    @Reference
    private MenuService menuService;

    /**
     * 获取登陆用户名
     */
    @GetMapping("/getUsername")
    public Result getUsername() {
        // 获取登陆用户的认证信息
        User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        // 登陆用户名
        String username = loginUser.getUsername();
        // 返回给前端
        return new Result(true, MessageConstant.GET_USERNAME_SUCCESS, username);
    }

    /**
     * 动态菜单
     *
     * @return
     */
    @GetMapping("/getMenu")
    public Result getMenu() {
        //security中获取用户名
        User loginUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        String username = loginUser.getUsername();

        com.liu.sunnyday.pojo.User user = userService.findByUsername(username);
        //取出角色
        Set<Role> roles = user.getRoles();
        //拿到角色后根据角色去取菜单，先设置一个集合接收菜单
        List<Menu> menus=null;
        for (Role role : roles) {
        //查每一个角色对应的角色
            menus=menuService.findByRoid(role.getId());
        }
        System.out.println("username:"+username);
        System.out.println("menus"+menus);

        return new Result(true,MessageConstant.GET_MENU_SUCCESS,menus);



    }


}
